<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板生成 - DocuGen</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/static/css/common.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jsoneditor@9.9.0/dist/jsoneditor.min.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-file-earmark-text me-2"></i>DocuGen
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/"><i class="bi bi-house me-1"></i>首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/document-generator"><i class="bi bi-file-earmark-text me-1"></i>文档生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/template-generator"><i class="bi bi-file-earmark-richtext me-1"></i>模板生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/qa"><i class="bi bi-chat-dots me-1"></i>智能问答</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="modelDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-gear me-1"></i>模型设置
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="modelDropdown">
                            <li><a class="dropdown-item model-switch" data-model="local" href="#"><i class="bi bi-cpu me-1"></i>本地模型</a></li>
                            <li><a class="dropdown-item model-switch" data-model="third_party" href="#"><i class="bi bi-cloud me-1"></i>第三方模型</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="container py-3">
            <div class="page-header mb-3">
                <h1 class="page-title"><i class="bi bi-file-earmark-richtext me-2"></i>模板生成</h1>
            </div>
            
            <div class="row">
                <div class="col-lg-12">
                    <div class="card mb-0">
                        <div class="card-header py-3">
                            <ul class="nav nav-tabs card-header-tabs mb-0" id="templateTabs" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="create-tab" data-bs-toggle="tab" data-bs-target="#create" type="button" role="tab">创建模板</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="use-tab" data-bs-toggle="tab" data-bs-target="#use" type="button" role="tab">使用模板</button>
                                </li>
                            </ul>
                        </div>
                        <div class="card-body py-3 px-4">
                            <div class="tab-content" id="templateTabsContent">
                                <!-- 创建模板选项卡 -->
                                <div class="tab-pane fade" id="create" role="tabpanel">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <div class="card mb-3">
                                                <div class="card-body">
                                                    <h6 class="card-title mb-3">上传模板</h6>
                                                    <form id="uploadTemplateForm" enctype="multipart/form-data">
                                                        <div class="mb-3">
                                                            <label for="templateName" class="form-label">模板名称</label>
                                                            <input type="text" class="form-control" id="templateName" placeholder="输入模板名称，如'项目报告'">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="templateFile" class="form-label">选择文件</label>
                                                            <input class="form-control" type="file" id="templateFile" accept=".docx">
                                                            <div class="form-text">请上传Word文档(.docx)格式</div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="templateDescription" class="form-label">描述(可选)</label>
                                                            <textarea class="form-control" id="templateDescription" rows="2" placeholder="添加简要描述"></textarea>
                                                        </div>
                                                        <div class="d-grid">
                                                            <button type="submit" class="btn btn-primary" id="uploadTemplateBtn">
                                                                <span class="spinner-border spinner-border-sm d-none" id="templateSpinner"></span>
                                                                <i class="bi bi-upload me-2"></i>上传模板
                                                            </button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                            <div class="card">
                                                <div class="card-body">
                                                    <h6 class="card-title mb-2">格式说明</h6>
                                                    <p class="mb-2"><i class="bi bi-info-circle-fill text-primary me-2"></i><strong>如何制作模板？</strong></p>
                                                    <p class="mb-1">在Word中使用 <code>【...】</code> (推荐) 或 <code>{{...}}</code> 标记变量：</p>
                                                    <ul class="mb-0">
                                                        <li>例如：<code>【标题】</code> 或 <code>{{Title}}</code></li>
                                                        <li class="form-text">推荐使用中文方括号 <code>【】</code> 以避免内容冲突。</li>
                                                        <li>生成时，占位符将被替换为实际内容。</li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="card mb-3">
                                                <div class="card-body">
                                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                                        <h6 class="card-title mb-0">可用模板列表</h6>
                                                        <button class="btn btn-outline-primary btn-sm" id="refreshTemplatesBtn">
                                                            <i class="bi bi-arrow-clockwise me-1"></i>刷新
                                                        </button>
                                                    </div>
                                                    <div class="table-responsive">
                                                        <table class="table table-sm table-hover mb-0">
                                                            <thead>
                                                                <tr>
                                                                    <th>模板名称</th>
                                                                    <th class="text-end">操作</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody id="templatesList">
                                                                <tr>
                                                                    <td colspan="2" class="text-center">暂无可用模板</td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="card">
                                                <div class="card-body">
                                                    <h6 class="card-title mb-3">创建结果</h6>
                                                    <div id="templateResult" class="d-none">
                                                        <div class="alert alert-success mb-0">
                                                            <h6><i class="bi bi-check-circle-fill me-2"></i>模板创建成功！</h6>
                                                            <p class="mb-2">模板名称: <span id="resultTemplateName"></span></p>
                                                            <p class="mb-3">您现在可以在"使用模板"标签页中使用此模板。</p>
                                                            <div class="d-grid gap-2">
                                                                <button class="btn btn-primary btn-sm" id="downloadTemplateBtn">
                                                                    <i class="bi bi-download me-2"></i>下载模板
                                                                </button>
                                                                <button class="btn btn-outline-primary btn-sm" id="switchToUseTabBtn">
                                                                    <i class="bi bi-arrow-right me-2"></i>立即使用
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div id="noTemplateResult">
                                                        <p class="text-muted text-center py-4 mb-0">
                                                            <i class="bi bi-info-circle me-1"></i>模板创建结果将显示在这里
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- 使用模板选项卡 -->
                                <div class="tab-pane fade show active" id="use" role="tabpanel">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <div class="card mb-3">
                                                <div class="card-body">
                                                    <h6 class="card-title mb-3">1. 选择模板</h6>
                                                    <select class="form-select" id="selectTemplate">
                                                        <option value="">-- 请选择模板 --</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="card mb-3">
                                                <div class="card-body">
                                                    <h6 class="card-title mb-3">2. 填充模板数据</h6>
                                                    
                                                    <!-- RAG选项 -->
                                                    <div class="border rounded p-3 mb-3">
                                                        <div class="d-flex align-items-center justify-content-between mb-3">
                                                            <span class="fw-bold">
                                                                <i class="bi bi-database me-2"></i>知识库增强
                                                            </span>
                                                            <button class="btn btn-sm btn-outline-primary" id="aiFillVariablesBtn">
                                                                <span class="spinner-border spinner-border-sm d-none" id="aiFillSpinner"></span> 
                                                                <i class="bi bi-magic me-1"></i> AI填充变量
                                                            </button>
                                                        </div>
                                                        <div class="form-check form-switch mb-3">
                                                            <input class="form-check-input" type="checkbox" id="useRag" checked>
                                                            <label class="form-check-label" for="useRag">使用RAG增强AI填充质量</label>
                                                        </div>
                                                        <div class="row g-2">
                                                            <div class="col-8">
                                                                <select class="form-select form-select-sm" id="ragSource" disabled>
                                                                    <option value="">加载知识库中...</option>
                                                                </select>
                                                            </div>
                                                            <div class="col-4">
                                                                <button class="btn btn-outline-primary btn-sm w-100" id="refreshKbBtn">
                                                                    <i class="bi bi-arrow-clockwise"></i> 刷新
                                                                </button>
                                                            </div>
                                                        </div>
                                                        <div class="mt-2" id="customRagSection" style="display: none;">
                                                            <textarea class="form-control form-control-sm" id="customRagInput" rows="2" placeholder="输入自定义知识库内容..."></textarea>
                                                        </div>
                                                    </div>
                                                    
                                                    <div id="templateVariablesContainer">
                                                        <div class="alert alert-info mb-0">
                                                            <i class="bi bi-info-circle me-2"></i>请先选择一个模板
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-grid">
                                                <button class="btn btn-primary" id="generateFromTemplateBtn" disabled>
                                                    <span class="spinner-border spinner-border-sm d-none" id="useTemplateSpinner"></span>
                                                    <i class="bi bi-file-earmark-richtext me-2"></i>生成文档
                                                </button>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="card">
                                                <div class="card-body">
                                                    <h6 class="card-title mb-3">生成结果</h6>
                                                    <div id="useTemplateResult" class="d-none">
                                                        <div class="alert alert-success mb-0">
                                                            <h6><i class="bi bi-check-circle-fill me-2"></i>文档生成成功！</h6>
                                                            <p class="mb-3">您的文档已经生成完毕，可以点击下方按钮下载。</p>
                                                            <div class="d-grid">
                                                                <button class="btn btn-primary" id="downloadGeneratedDocBtn">
                                                                    <i class="bi bi-download me-2"></i>下载生成的文档
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div id="noUseTemplateResult">
                                                        <p class="text-muted text-center py-5 mb-0">
                                                            <i class="bi bi-info-circle me-1"></i>文档生成结果将显示在这里
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="py-4">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="bi bi-file-earmark-text me-2"></i>DocuGen</h5>
                    <p>AI驱动的文档生成系统，让创作更高效。</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p class="mb-0">&copy; 2023 DocuGen. 保留所有权利。</p>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsoneditor@9.9.0/dist/jsoneditor.min.js"></script>
    <script>
        $(document).ready(function() {
            // 当前模型类型
            let currentModel = 'third_party';
            
            // 当前生成的模板路径
            let currentTemplatePath = '';
            let currentGeneratedDocPath = '';
            
            // 页面加载时立即获取
            refreshTemplatesList();
            loadKnowledgeBases();
            
            // 上传模板
            $('#uploadTemplateForm').on('submit', function(e) {
                e.preventDefault();
                
                const templateName = $('#templateName').val().trim();
                const templateFile = $('#templateFile')[0].files[0];
                const templateDescription = $('#templateDescription').val().trim();
                
                if (!templateName) {
                    alert('请输入模板名称');
                    return;
                }
                
                if (!templateFile) {
                    alert('请选择模板文件');
                    return;
                }
                
                // 检查文件类型
                if (!templateFile.name.endsWith('.docx')) {
                    alert('请上传Word文档(.docx)格式的模板文件');
                    return;
                }
                
                // 显示加载动画
                $('#templateSpinner').removeClass('d-none');
                $('#uploadTemplateBtn').prop('disabled', true);
                
                // 创建FormData对象用于文件上传
                const formData = new FormData();
                formData.append('template_name', templateName);
                formData.append('template_file', templateFile);
                formData.append('description', templateDescription);
                
                // 发送请求上传模板
                $.ajax({
                    url: '/api/upload-template',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            // 更新UI显示结果
                            $('#noTemplateResult').addClass('d-none');
                            $('#templateResult').removeClass('d-none');
                            $('#resultTemplateName').text(response.template_name);
                            
                            // 保存文件名用于下载
                            currentTemplatePath = response.filename;
                            
                            // 刷新模板列表
                            refreshTemplatesList();
                        } else {
                            alert('上传模板失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('请求失败: ' + xhr.responseText);
                    },
                    complete: function() {
                        $('#templateSpinner').addClass('d-none');
                        $('#uploadTemplateBtn').prop('disabled', false);
                    }
                });
            });
            
            // 刷新模板列表
            function refreshTemplatesList() {
                $.ajax({
                    url: '/api/templates',
                    type: 'GET',
                    success: function(response) {
                        if (response.templates && response.templates.length > 0) {
                            // 更新表格
                            let html = '';
                            response.templates.forEach(function(template) {
                                html += `
                                <tr>
                                    <td>${template}</td>
                                    <td class="text-end">
                                        <button class="btn btn-sm btn-outline-primary use-template-btn" data-template="${template}">
                                            <i class="bi bi-file-earmark-text me-1"></i>使用
                                        </button>
                                    </td>
                                </tr>`;
                            });
                            $('#templatesList').html(html);
                            
                            // 更新下拉菜单
                            let selectHtml = '<option value="">-- 请选择模板 --</option>';
                            response.templates.forEach(function(template) {
                                selectHtml += `<option value="${template}">${template}</option>`;
                            });
                            $('#selectTemplate').html(selectHtml);
                        } else {
                            $('#templatesList').html('<tr><td colspan="2" class="text-center">暂无可用模板</td></tr>');
                            $('#selectTemplate').html('<option value="">-- 请选择模板 --</option>');
                        }
                    },
                    error: function(xhr) {
                        alert('获取模板列表失败: ' + xhr.responseText);
                    }
                });
            }
            
            // 点击刷新按钮
            $('#refreshTemplatesBtn').on('click', function() {
                refreshTemplatesList();
            });
            
            // 点击下载模板按钮
            $('#downloadTemplateBtn').on('click', function() {
                if (currentTemplatePath) {
                    const filename = currentTemplatePath.split('/').pop();
                    window.location.href = '/download/' + filename;
                } else {
                    alert('找不到模板文件');
                }
            });
            
            // 切换到使用模板选项卡
            $('#switchToUseTabBtn').on('click', function() {
                $('#use-tab').tab('show');
                // 切换标签页时刷新模板列表
                refreshTemplatesList();
            });
            
            // 从列表中选择模板
            $(document).on('click', '.use-template-btn', function() {
                const template = $(this).data('template');
                $('#selectTemplate').val(template);
                $('#use-tab').tab('show');
                loadTemplateVariables(template);
            });
            
            // 选择模板下拉菜单变化
            $('#selectTemplate').on('change', function() {
                const templateName = $(this).val();
                if (templateName) {
                    loadTemplateVariables(templateName);
                } else {
                    // 刷新模板列表以确保下拉菜单是最新的
                    refreshTemplatesList();
                    $('#templateVariablesContainer').html(
                        '<div class="alert alert-info"><i class="bi bi-info-circle me-2"></i>请先选择一个模板</div>'
                    );
                    $('#generateFromTemplateBtn').prop('disabled', true);
                }
            });
            
            // 加载模板变量
            function loadTemplateVariables(templateName) {
                $('#templateVariablesContainer').html(
                    '<div class="text-center py-3"><span class="spinner-border spinner-border-sm me-2"></span>正在加载模板变量...</div>'
                );
                
                // 禁用AI填充按钮直到变量加载完成
                $('#aiFillVariablesBtn').prop('disabled', true);
                
                $.ajax({
                    url: '/api/get-template-variables',
                    type: 'GET',
                    data: { template_name: templateName },
                    success: function(response) {
                        if (response.variables && response.variables.length > 0) {
                            let html = '<form id="templateVariablesForm">';
                            response.variables.forEach(function(variable, index) {
                                html += `
                                <div class="mb-3">
                                    <label for="var_${index}" class="form-label">${variable.description || variable.name}</label>
                                    <input type="text" class="form-control template-variable-input" 
                                           id="var_${index}" name="${variable.name}" 
                                           placeholder="请输入${variable.name}的值" 
                                           value="${variable.default_value || ''}" required>
                                </div>`;
                            });
                            html += '</form>';
                            $('#templateVariablesContainer').html(html);
                            
                            // 绑定输入事件
                            $('.template-variable-input').on('input', function() {
                                const allFilled = areAllVariablesFilled();
                                $('#generateFromTemplateBtn').prop('disabled', !allFilled);
                            });
                            
                            // 初始检查是否所有字段都已填写
                            const allFilled = areAllVariablesFilled();
                            $('#generateFromTemplateBtn').prop('disabled', !allFilled);
                            
                            // 启用AI填充按钮
                            $('#aiFillVariablesBtn').prop('disabled', false);
                        } else {
                            $('#templateVariablesContainer').html(
                                '<div class="alert alert-warning"><i class="bi bi-exclamation-triangle me-2"></i>此模板没有定义变量</div>'
                            );
                            $('#generateFromTemplateBtn').prop('disabled', false);
                            // 禁用AI填充按钮
                            $('#aiFillVariablesBtn').prop('disabled', true);
                        }
                    },
                    error: function(xhr) {
                        $('#templateVariablesContainer').html(
                            `<div class="alert alert-danger"><i class="bi bi-x-circle me-2"></i>获取模板变量失败: ${xhr.responseText}</div>`
                        );
                        $('#generateFromTemplateBtn').prop('disabled', true);
                        // 禁用AI填充按钮
                        $('#aiFillVariablesBtn').prop('disabled', true);
                    }
                });
            }
            
            // 检查是否所有必填变量都已填写 (AI填充后可能不需要强制必填)
            function areAllVariablesFilled() {
                // 如果需要，可以在这里添加逻辑检查AI填充后的字段
                return true; // 暂时总是返回true，假设AI能填充所有必要字段
            }
            
            // AI填充变量
            $('#aiFillVariablesBtn').on('click', function() {
                const templateName = $('#selectTemplate').val();
                if (!templateName) {
                    alert('请先选择一个模板');
                    return;
                }
                
                // 显示加载动画
                $('#aiFillSpinner').removeClass('d-none');
                $('#aiFillVariablesBtn').prop('disabled', true);
                $('#generateFromTemplateBtn').prop('disabled', true);
                
                // 准备请求数据
                const requestData = {
                    template_name: templateName,
                    enable_rag: $('#useRag').is(':checked'),
                    kb_name: $('#ragSource').val()
                };
                
                // 如果选择了自定义知识，添加自定义内容
                if (requestData.enable_rag && requestData.kb_name === 'custom') {
                    requestData.custom_rag_content = $('#customRagInput').val();
                }
                
                // 发送请求
                $.ajax({
                    url: '/api/ai-fill-template-variables',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(requestData),
                    success: function(response) {
                        console.log('AI填充响应:', response); // 添加调试日志
                        
                        if (response.success && response.variables) {
                            // 遍历所有变量并更新表单
                            for (const [varName, varValue] of Object.entries(response.variables)) {
                                console.log(`更新变量: ${varName} = ${varValue}`); // 添加调试日志
                                const inputField = $(`input[name="${varName}"]`);
                                if (inputField.length > 0) {
                                    inputField.val(varValue);
                                    // 手动触发 change 事件
                                    inputField.trigger('change');
                                } else {
                                    console.warn(`未找到变量输入框: ${varName}`); // 添加调试日志
                                }
                            }
                            
                            // 显示成功消息
                            const successAlert = $('<div>')
                                .addClass('alert alert-success alert-dismissible fade show mt-3')
                                .html(`
                                    <i class="bi bi-check-circle-fill me-2"></i>AI 已成功填充变量值
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                `);
                            $('#templateVariablesContainer').prepend(successAlert);
                            
                            // 启用生成按钮
                            $('#generateFromTemplateBtn').prop('disabled', false);
                        } else {
                            // 显示错误消息
                            const errorMsg = response.error || '未知错误';
                            const errorAlert = $('<div>')
                                .addClass('alert alert-danger alert-dismissible fade show mt-3')
                                .html(`
                                    <i class="bi bi-exclamation-triangle-fill me-2"></i>AI 填充失败: ${errorMsg}
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                `);
                            $('#templateVariablesContainer').prepend(errorAlert);
                        }
                    },
                    error: function(xhr) {
                        console.error('AI填充请求失败:', xhr); // 添加调试日志
                        
                        // 显示错误消息
                        const errorAlert = $('<div>')
                            .addClass('alert alert-danger alert-dismissible fade show mt-3')
                            .html(`
                                <i class="bi bi-exclamation-triangle-fill me-2"></i>AI 填充请求失败: ${xhr.responseText}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            `);
                        $('#templateVariablesContainer').prepend(errorAlert);
                    },
                    complete: function() {
                        $('#aiFillSpinner').addClass('d-none');
                        $('#aiFillVariablesBtn').prop('disabled', false);
                    }
                });
            });
            
            // RAG开关事件处理
            $('#useRag').on('change', function() {
                const useRag = $(this).is(':checked');
                $('#ragSource').prop('disabled', !useRag);
                if (useRag && $('#ragSource').val() === 'custom') {
                    $('#customRagSection').show();
                } else {
                    $('#customRagSection').hide();
                }
            });

            // 知识库选择事件处理
            $('#ragSource').on('change', function() {
                const isCustom = $(this).val() === 'custom';
                $('#customRagSection').toggle(isCustom);
            });
            
            // 刷新知识库列表
            $('#refreshKbBtn').on('click', function() {
                loadKnowledgeBases();
            });

            // 加载知识库列表函数
            function loadKnowledgeBases() {
                $.ajax({
                    url: '/api/kb/list',
                    type: 'GET',
                    success: function(response) {
                        if (response.success && response.data) {
                            const $select = $('#ragSource');
                            $select.empty();
                            
                            $select.append('<option value="custom">自定义知识库内容</option>');
                            
                            if (Array.isArray(response.data)) {
                                if (response.data.length > 0) {
                                    response.data.forEach(function(kb) {
                                        $select.append(`<option value="${kb}">${kb}</option>`);
                                    });
                                } else {
                                    $select.append('<option value="">没有可用的知识库</option>');
                                }
                            } else {
                                $select.append('<option value="">数据格式错误</option>');
                            }
                            
                            $select.prop('disabled', !$('#useRag').is(':checked'));
                        } else {
                            $('#ragSource').html('<option value="">加载知识库失败</option>');
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#ragSource').html('<option value="">加载知识库失败</option>');
                    }
                });
            }
            
            // 生成文档
            $('#generateFromTemplateBtn').on('click', function() {
                const templateName = $('#selectTemplate').val();
                if (!templateName) {
                    alert('请选择模板');
                    return;
                }
                
                // 收集变量值
                const variableData = {};
                $('#templateVariablesForm').find('input').each(function() {
                    variableData[$(this).attr('name')] = $(this).val().trim();
                });
                
                // 显示加载动画
                $('#useTemplateSpinner').removeClass('d-none');
                $('#generateFromTemplateBtn').prop('disabled', true);
                
                // 创建FormData对象
                const formData = new FormData();
                formData.append('template_name', templateName);
                formData.append('data', JSON.stringify(variableData));
                
                // 发送生成请求
                $.ajax({
                    url: '/api/generate-from-template',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.filename) {
                            $('#noUseTemplateResult').addClass('d-none');
                            $('#useTemplateResult').removeClass('d-none');
                            currentGeneratedDocPath = response.filename;
                        } else {
                            alert('生成文档失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('请求失败: ' + xhr.responseText);
                    },
                    complete: function() {
                        $('#useTemplateSpinner').addClass('d-none');
                        $('#generateFromTemplateBtn').prop('disabled', false);
                    }
                });
            });
            
            // 下载生成的文档
            $('#downloadGeneratedDocBtn').on('click', function() {
                if (currentGeneratedDocPath) {
                    const filename = currentGeneratedDocPath.split('/').pop();
                    window.location.href = '/download/' + filename;
                } else {
                    alert('找不到生成的文档');
                }
            });
            
            // 模型切换
            $('.model-switch').on('click', function(e) {
                e.preventDefault();
                const modelType = $(this).data('model');
                if (modelType === currentModel) return;
                
                $.ajax({
                    url: '/api/switch-model',
                    type: 'POST',
                    data: { model_type: modelType },
                    success: function(response) {
                        if (response.success) {
                            currentModel = modelType;
                            alert(`已切换到${modelType === 'local' ? '本地模型' : '第三方模型'}`);
                        } else {
                            alert('模型切换失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('模型切换请求失败: ' + xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>